﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.Text;

namespace Thor.Models
{
    public class RSAEncryption
    {
        private CspParameters _csp;
        RSACryptoServiceProvider _rscp;
        public RSAEncryption(string containerId)
        {
            _csp = new CspParameters();
            _csp.KeyContainerName = containerId;
            _rscp = new RSACryptoServiceProvider(_csp);
        }

        public RSAParameters GetPublicKey(string containerId)
        {
            return _rscp.ExportParameters(false);
        }
        public string Decrypt(byte[] data)
        {
            byte [] result = _rscp.Decrypt(data, false);
            System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
            return enc.GetString(result); 
        }
        public static byte[] AsciiToByteArray(string value)
        {
            int numberChars = value.Length;
            byte[] bytes = new byte[numberChars / 2];
            for (int i = 0; i < numberChars; i += 2)
                bytes[i / 2] = Convert.ToByte(value.Substring(i, 2), 16);
            return bytes;
        }
        public static string HexToAsciiArray(byte[] value)
        {
            StringBuilder result = new StringBuilder(value.Length * 2);
            foreach (byte b in value)
                result.AppendFormat("{0:x2}", b);
            return result.ToString();
        }

    }
}

